package dao;

import entity.IEntity;
import entity.Task;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author Alexander
 */
public class TaskDAO implements IDAO {

    @Override
    public void persist(IEntity entity, EntityManager em) {
        em.persist(entity);
    }

    @Override
    public IEntity find(Object id, EntityManager em) {
        return (Task) em.find(Task.class, (int) id);
    }

    @Override
    public void update(IEntity entity, EntityManager em) {
        em.merge(entity);
    }

    @Override
    public void delete(Object id, EntityManager em) {
        Task tarea = (Task) em.getReference(Task.class, (int) id);
        em.remove(tarea);
    }

    @Override
    public List<IEntity> getList(EntityManager em) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Task.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    }

    public List<Task> getTaskByDate(Date date, EntityManager em) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String d = format.format(date);
        List<Task> tasks = new ArrayList<>();
        Query q = em.createQuery("SELECT m FROM Task m "
                    + "WHERE m.startDate LIKE :date").setParameter("date", d);
        try {
            tasks = q.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tasks;
    }
}
